package com.kasax.httpsupport;

import android.os.Handler;
import android.os.Looper;

import java.io.IOException;

public interface IResponseHandler {
    /**
     * 线程切换,http请求成功时的回调
     *
     * @param callback &emsp;回调接口
     * @param response &emsp;返回结果
     */
    void handlerSuccess(Callback callback, Response response);


    /**
     * 线程切换,http请求失败时候的回调
     *
     * @param callback &emsp;回调接口
     * @param request  &emsp;请求
     * @param e        &emsp;可能产生的异常
     */
    void handleFail(Callback callback, Request request, IOException e);

    IResponseHandler RESPONSE_HANDLER = new IResponseHandler() {
        private Handler HANDLER = new Handler(Looper.getMainLooper());

        @Override
        public void handlerSuccess(Callback callback, Response response) {
            execute(new Runnable() {
                @Override
                public void run() {
                    callback.onReponse(response);
                }
            });
        }

        @Override
        public void handleFail(Callback callback, Request request, IOException e) {
            execute(new Runnable() {
                @Override
                public void run() {
                    callback.onFailure(request, e);
                }
            });
        }

        /**
         * 线程切换
         */
        public void execute(Runnable r) {
            HANDLER.post(r);
        }

        public void removeAllMessage() {
            HANDLER.removeCallbacksAndMessages(null);
        }
    };
}
